#-------------------------------------------------------------------------------
# Name:        moddt8837
# Purpose:
#
# Author:      patrick
#
# Created:     22/05/2012
# Copyright:   (c) patrick 2012
# Licence:     <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python

from pyvisa.visa import *
from pyvisa import vpp43
import numpy as np
import scipy as sc
#-------------------------------------------------------------------------------
#retourne le handle du boitier
#-------------------------------------------------------------------------------
def getHandle(dev):
    h=instrument(dev)
    return h

#-------------------------------------------------------------------------------
# recupere le nom du boitier
#-------------------------------------------------------------------------------
def getID(h):
    h.write("*IDN?")
    s = h.read()
    return s

#-------------------------------------------------------------------------------
# RSET des modules
#-------------------------------------------------------------------------------
def doRST(h):
    err = h.write ("*RST")
    if err is not None:
        print 'Erreur initialisation...'
    return err

#-------------------------------------------------------------------------------
# Enable AD for all channel
#-------------------------------------------------------------------------------
def setAdEnableAll(h):
    err = h.write(":AD:ENAB ON,(@1,2,3,4)") # active channel 1 ,2,3,4
    if err is not None:
        print 'Erreur activation AD module...'
    return err

#-------------------------------------------------------------------------------
# couplage AC/DC pour tous les moduls
#-------------------------------------------------------------------------------
def setCouplage(h,type):
    s=":AD:COUP "+type+",(@1,2,3,4)"
    err = h.write(s)  # couplage AC/DC
    if err is not None:
        print 'Erreur couplage AC/DC...'
    return err

#-------------------------------------------------------------------------------
# mode acquisition wrap /no wrap
#-------------------------------------------------------------------------------
def setWrap(h,flag):
    if flag =='on':
        err=h.write(":AD:BUFF:MODE wrap")
    if flag =='off':
        err=h.write(":AD:BUFF:MODE nowrap")
    if err is not None:
        print 'Erreur buffer wrap...'
    return err

#-------------------------------------------------------------------------------
# initialisation des gains pour toutes les voies  1/10
#-------------------------------------------------------------------------------
def setGain(h,level):
    s=":AD:GAIN "+str(level)+",(@1,2,3,4)"
    err = h.write(s)
    if err is not None:
        print 'Erreur initialisation des gains...'
    return err

#-------------------------------------------------------------------------------
# horloge interne
#-------------------------------------------------------------------------------
def setADClockInternal(h):
    err=h.write(":AD:CLOCK:SOURCE INTERNAL")
    if err is not None:
        print 'Erreur initialisation horloge interne...'
    return err

#-------------------------------------------------------------------------------
# frequence horloge interne
#-------------------------------------------------------------------------------
def setFreqClock(h,freq):
    s=":AD:CLOC:FREQ "+str(freq)
    err=h.write(s)  #initialise la frequence echantillonnage
    if err is not None:
        print 'Erreur initialisation frequence horloge interne...'
    return err

#-------------------------------------------------------------------------------
# trigger immediat / software
#-------------------------------------------------------------------------------
def setAdTrigSourceImm(h):
    err=h.write(":AD:TRIG IMM")
    if err is not None:
        print 'Erreur initialisation trigger source immediat...'
    return err

#-------------------------------------------------------------------------------
# pret a lancer la mesure
#-------------------------------------------------------------------------------
def setAdArm(h):
    err=h.write(":AD:ARM")
    if err is not None:
        print 'Erreur AD armement...'
    return err


#-------------------------------------------------------------------------------
# lance la mesure la mesure
#-------------------------------------------------------------------------------
def setAdInit(h):
    err=h.write(":AD:INIT")
    if err is not None:
        print 'Erreur AD init, lance la mesure...'
    return err


#-------------------------------------------------------------------------------
# arrete la mesure la mesure
#-------------------------------------------------------------------------------
def setAdStop(h):
    err=h.write(":AD:ABORT")
    if err is not None:
        print 'Erreur AD abort, arrete la mesure...'
    return err

def readHeader(data):
    # lecture entete fichier norme IEEE488.2
    # #xyyyyyyy
    s=struct.unpack_from('2c',data)
    sizeHeader=int(s[1])
    # lecture taille du bloc de data suivant
    fmt=str(sizeHeader)+"c"
    s=struct.unpack_from(fmt,data[2:])
    L=len(s)
    sizeBuffer=0
    for i in range(L):
        sizeBuffer = pow(10,i)*int(s[L-i-1]) + sizeBuffer
    #lecture des 5 champ de 4 byte qui contituent le header
    fmt=">5l"
    header=struct.unpack_from(fmt,data[8:])
    header = np.array(header)
    header=sc.reshape(header,(1,5))
    # header(0) = index of first scan record in this block
    # header(1) = Number of scan records in this block
    # header(2) = Number of samples per enabled channel or scan record
    # header(3) = Time stamp of the first scan record in the block, in second
    # header(4) =  Time stamp of the first scan record in the block, in second
    bufsize = sizeBuffer - 28 # 2+6+5*4
    fmt=">"+str(bufsize/4)+"I"
    buf=struct.unpack_from(fmt,data[28:])
    buf=np.array(buf)
    taille=bufsize/4
    buf=buf[1::4]
##    print "taille buf = ",buf.shape
    return sizeHeader,sizeBuffer,header,buf
    
def GetAdBufferStatus(h):    
    err = h.write(":AD:STAT?;:AD:STAT:SCAN?")
    if err is not None:
        print 'Erreur AD getAdBufferStatus...'
    s = h.read()
    s=s.split(";")
    ADstatus=int(s[0])
    s=s[1]
    s=s.split(",")
    ideb, ifin = int(s[0]), int(s[1])
    return ADstatus, ideb, ifin

# testBit() returns a nonzero result, 2**offset, if the bit at 'offset' is one.

def testBit(int_type, offset):
    mask = 1 << offset
    return(int_type & mask)

# setBit() returns an integer with the bit at 'offset' set to 1.

def setBit(int_type, offset):
    mask = 1 << offset
    return(int_type | mask)

# clearBit() returns an integer with the bit at 'offset' cleared.

def clearBit(int_type, offset):
    mask = ~(1 << offset)
    return(int_type & mask)

# toggleBit() returns an integer with the bit at 'offset' inverted, 0 -> 1 and 1 -> 0.

def toggleBit(int_type, offset):
    mask = 1 << offset
    return(int_type ^ mask)
